/*
 * ExecutorService.cpp
 *
 *  Created on: Sep 17, 2016
 *      Author: root
 */

#include "yExecutorService.h"
#include <pthread.h>
ExecutorService::ExecutorService(int n) :
		queue(1024), threadNum(n), running(true) {
	worker = new pthread_t[threadNum];
	for (int i = 0; i < threadNum; i++) {
		pthread_create(worker + i, NULL, &ExecutorService::createWorkerThread, this);
	}
//	for (int i = 0; i < threadNum; ++i) {
//		pthread_join(worker[i], NULL);
//	}
}

ExecutorService* ExecutorService::newFixedThreadPool(int n) {
	return new ExecutorService(n);
}

void ExecutorService::excute(task* tsk) {
	queue.put(tsk);
}

void ExecutorService::shutdown() {
	running = false;
}

ExecutorService::~ExecutorService() {
	SAFE_DELETE_ARRAY(worker);
}

void* ExecutorService::createWorkerThread(void* arg) {
	ExecutorService* instance = (ExecutorService*) arg;
	while (instance->running) {
		task* tsk = (task*) instance->queue.take();
		if (tsk) {
			tsk->rFun(tsk->data);
		}
	}
	return NULL;
}
